package org.jxkj.utils;

import org.apache.log4j.Logger;
import org.jxkj.bean.Point;
import org.jxkj.util.PropertiesUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;
import java.util.Properties;

public class RedisUtils {
    //配置redis基本连接参数

    private static JedisPoolConfig config = new JedisPoolConfig();
    private static JedisPool jedisPool ;
    private static final Logger logger = Logger.getLogger(RedisUtils.class);
    static {
        //设置允许最大的连接个数
        config.setMaxTotal(100);
        //最大空闲连接数
        config.setMaxIdle(50);
        //最小空闲连接数
        config.setMinIdle(8);
        //设置连接时的最大等待毫秒数
        config.setMaxWaitMillis(-1);
        //设置在获取连接时，是否检查连接的有效性
        config.setTestOnBorrow(true);
        //设置释放连接到池中时是否检查有效性
        config.setTestOnReturn(true);
        //在连接空闲时，是否检查连接有效性
        config.setTestWhileIdle(true);
        //两次扫描之间的时间间隔毫秒数
        config.setTimeBetweenEvictionRunsMillis(30000);
        //每次扫描的最多的对象数
        config.setNumTestsPerEvictionRun(10);
        //逐出连接的最小空闲时间，默认是180000（3分钟）
        config.setMinEvictableIdleTimeMillis(180000);
        Properties properties = PropertiesUtils.initial("redis.properties");
        String host = PropertiesUtils.getProperty("redis.host",properties);
        String port = PropertiesUtils.getProperty("redis.port",properties);
        String timeout = PropertiesUtils.getProperty("redis.timeout",properties);
        String pw = PropertiesUtils.getProperty("redis.pw",properties);
        //jedisPool = new JedisPool(config,host,Integer.valueOf(port),Integer.valueOf(timeout),"Hms@2019");
        jedisPool = new JedisPool(config,host,Integer.valueOf(port),Integer.valueOf(timeout),pw);
    }


    /**
     * 获取Jedis实例
     * @return
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResourceObject(jedis);
        }
    }


    /**
     * 向缓存中设置字符串内容
     *
     * @param key
     *            key
     * @param value
     *            value
     * @return
     * @throws Exception
     */
    public static boolean set(String key, String value,Jedis jedis) {
        try {
            if(jedis != null){
                jedis.set(key, value);
            }
            return true;
        } catch (Exception e) {
            logger.error("Redis缓存设置key值 出错！",e);
            return false;
        }
    }


    /**
     * 根据key 获取内容
     *@param jedis
     * @param key
     * @return
     */
    public static String get(String key,Jedis jedis) {
        try {
            String value = jedis.get(key);
            return value;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据key 获取内容
     * @param key
     * @return
     */
    public static String get(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            String value = jedis.get(key);
            return value;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            returnResource(jedis);
        }
        return null;
    }


    /**
     * 判断key是否存在
     */
    public static boolean exists(String key){
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (jedis == null) {
                return false;
            } else {
                return jedis.exists(key);
            }
        } catch (Exception e) {
            logger.error("Redis缓存判断key是否存在 出错！", e);
            return false;
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 删除缓存中的对象，根据key
     * @param key
     * @return
     */
    public static boolean del(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.del(key);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            returnResource(jedis);
        }
    }



    /**
     * 初始化该任务在redis中的数据
     * 在redis中配置全局点名与pointid的对应关系
     * @param
     */
    public static void initialRedis(int taksId){
        Point p = new Point();
        List<Point> points = p.getListPoint(taksId);
        //获取jedis
            Jedis jedis = RedisUtils.getJedis();
            for (Point point : points) {
                int pointId = point.getPointId();
                String pointName = point.getPointName();
                System.out.print("pointName"+pointName+pointId);
                RedisUtils.set(pointName,String.format("%06d", pointId),jedis);
            }
            RedisUtils.returnResource(jedis);
    }
}
